package com.zhiyou.aifeng.smart_machine

import android.os.Build
import android.os.Bundle
import com.jeremyliao.liveeventbus.LiveEventBus
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.zhiyou.aifeng.common.base.oneClick
import com.zhiyou.aifeng.common.helper.*
import com.zhiyou.aifeng.common_ui.base.BaseActivity
import com.zhiyou.aifeng.common_ui.base.addItems
import com.zhiyou.aifeng.common_ui.base.loadImage
import com.zhiyou.aifeng.common_ui.model.BaseUrl
import com.zhiyou.aifeng.common_ui.oss.OSSHelper
import com.zhiyou.aifeng.common_ui.oss.scaleMImage
import com.zhiyou.aifeng.common_ui.utils.bindLifeCycle
import com.zhiyou.aifeng.common_ui.utils.showAreaDialog
import com.zhiyou.aifeng.common_ui.utils.subscribeByFinally
import com.zhiyou.aifeng.utils.GlideEngine
import com.zhiyou.aifeng.utils.PictureSelectConst
import com.zhiyou.aifeng.utils.callback
import com.zhiyou.aifeng.viewmodel.RealViewModel
import kotlinx.android.synthetic.main.activity_real.*
import org.jetbrains.anko.longToast
import org.jetbrains.anko.toast

class RealActivity : BaseActivity() {

    private var mImg1 = ""
    private var mImg2 = ""
    private var mImg3 = ""

    private val areaIds = ArrayList<String>()
    private var mRegion = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_real)
        initTitle(title = "信息认证", divider = false)
    }

    override fun getViewModel() = get<RealViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        real_name.setText(getString("realName"))
        real_num.setText(getString("idCard"))
        real_tel.setRightString(getString("phone"))
        real_num.setSelection(real_num.text.length)

        initListener()
    }

    override fun initListener() {
        real_area_ll.oneClick {
            getViewModel().getAreaList()
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByFinally(
                    event = getViewModel(),
                    onSuccess = {
                        showAreaDialog(
                            items = it,
                            onResult = { ids, adress ->
                                areaIds.clear()
                                areaIds.addItems(ids)
                                mRegion = adress

                                real_area.text = mRegion
                            }
                        )
                    }
                )
        }
        real_img1.oneClick { openGallery(1) }
        real_img2.oneClick { openGallery(2) }
        real_img3.oneClick { openGallery(3) }
        bt_submit.oneClick {
            when {
                real_name.text.isBlank() -> {
                    real_name.requestFocus()
                    toast("请输入真实姓名")
                    return@oneClick
                }
                real_num.text.isEmpty() -> {
                    real_num.requestFocus()
                    toast("请输入身份证号码")
                    return@oneClick
                }
                mRegion.isEmpty() -> {
                    toast("请选择所在地区")
                    return@oneClick
                }
                mImg1.isEmpty() -> {
                    toast("请上传身份证合照片")
                    return@oneClick
                }
                mImg2.isEmpty() -> {
                    toast("请上传身份证正面照片")
                    return@oneClick
                }
                mImg3.isEmpty() -> {
                    toast("请上传身份证反面照片")
                    return@oneClick
                }
                !CommonUtil.IDCardValidate(real_num.textString()) -> {
                    real_num.requestFocus()
                    toast("请输入正确的身份证号码")
                    return@oneClick
                }
            }

            getViewModel().request(
                requestUrl = BaseUrl.auth,
                params = *arrayOf(
                    "uid" to getString("userId"),
                    "name" to real_name.trimString(),
                    "number" to real_num.textString(),
                    "idfront" to mImg2,
                    "idback" to mImg3,
                    "idgroup" to mImg1,
                    "province" to areaIds[0],
                    "city" to areaIds[1],
                    "district" to areaIds[2],
                    "town" to areaIds[3],
                    "village" to areaIds[4],
                    "regoin_addr" to mRegion,
                    "address" to real_detail.trimString()
                ),
                onResult = {
                    longToast("您的认证信息已提交，请耐心等待！")
                    putShared("auth", "1")
                    LiveEventBus.get("authState").post("submit")
                    finishView()
                }
            )
        }
    }

    private fun openGallery(type: Int) {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofImage())
            .imageEngine(GlideEngine.createGlideEngine())
            .theme(R.style.Picture_Green_Style)
            .isWeChatStyle(false)
            .isUseCustomCamera(false)
            .isMaxSelectEnabledMask(false)
            .maxSelectNum(1)
            .selectionMode(PictureConfig.SINGLE)
            .isCamera(true)
            .apply {
                if (Build.BRAND == "LeEco"
                    && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
                ) {
                    setOutputCameraPath(PictureSelectConst.getSavePath())
                }
            }
            .isCompress(true)
            .isGif(false)
            .isEnableCrop(true)
            .withAspectRatio(5, 3)
            .hideBottomControls(true)
            .circleDimmedLayer(false)
            .showCropFrame(true)
            .showCropGrid(true)
            .isOpenClickSound(false)
            .cutOutQuality(90)
            .minimumCompressSize(100)
            .callback {
                onResult {
                    val media = it[0]

                    OSSHelper.manager.uploadImage(
                        path = if (media.isCompressed) media.compressPath else media.cutPath,
                        onBefore = { showLoading("正在上传中...") },
                        onAfter = { dismissLoading() },
                        onSuccess = { result ->
                            when (type) {
                                1 -> {
                                    mImg1 = result.responseHeader["url"].orEmpty()
                                    real_img1.loadImage(mImg1.scaleMImage())
                                }
                                2 -> {
                                    mImg2 = result.responseHeader["url"].orEmpty()
                                    real_img2.loadImage(mImg2.scaleMImage())
                                }
                                3 -> {
                                    mImg3 = result.responseHeader["url"].orEmpty()
                                    real_img3.loadImage(mImg3.scaleMImage())
                                }
                            }
                        },
                        OnError = { toast("网络异常，请稍候再试！") }
                    )
                }
            }
    }

}